﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace PMS.Utils
{
    public class ConfigEngine
    {
        string FileName = "DataConfig.dat";
        string folderName = "PMS";
        public string GetFileName(string folder,string file)
        {
            string path = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);

            if (!Directory.Exists(path + @"\" + folder))
            {
                Directory.CreateDirectory(path + @"\" + folder);
            }

            if (!File.Exists(path + @"\" + folder + @"\" + file))
            {
                File.Create(path + @"\" + folder + @"\" + file);
            }

            return path + @"\" + folder + @"\" + file;
        }
        public Dictionary<string,string> ReadConnectingString()
        {
            try
            {
                Dictionary<string, string> connection = new Dictionary<string, string>();
                string path = GetFileName(folderName, FileName);
                StreamReader f = new StreamReader(path);
                string line;
                while((line=f.ReadLine())!=null)
                {
                        string[] keyvalue = line.Split('=');
                        connection.Add(keyvalue[0], keyvalue[1]);

                }

                
                return connection;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message, ex);
            }
        }

        public bool WriteConnectingString(Dictionary<string,string> connectiong)
        {
            try
            {
                string path = GetFileName(folderName, FileName);
                using (StreamWriter wt = new StreamWriter(path))
                {

                    wt.WriteLine("Data Source=" + connectiong["Data Source"]);
                    wt.WriteLine("Initial Catalog=" + connectiong["Initial Catalog"]);
                    wt.WriteLine("User Id=" + connectiong["User Id"]);
                    wt.WriteLine("Password=" + connectiong["Password"]);
                }
                return true;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message, ex);
            }
        }

        public string Connectingstring(Dictionary<string, string> connecting)
        {
            return "Data Source=" + connecting["Data Source"] + ";Initial Catalog=" + connecting["Initial Catalog"] + ";User Id=" + connecting["User Id"] + ";Password=" + connecting["Password"];
        }
    }
}
